import { defineStore } from 'pinia'
import { getOrderList, createOrderBuynow, createOrderFromCart, deleteOrder, applyAfterSale } from '@/api/order'
import { ElMessage } from 'element-plus'
export const userOrderStore = defineStore('order', {
  state: () => ({
    orders: [],
  }),
  actions: {
    async fetchOrders() {
      const response = await getOrderList()
      console.log("获取订单列表的请求的结果：", response);
      console.log("获取订单列表的请求的结果内容：", response.data);
      if (response.data.code === 0) {
        this.orders = response.data.data
        const orderStatus = this.orders.filter(item => item.orderStatus === 6 || item.orderStatus === 7)
        console.log("售后订单列表：", orderStatus);



        return true
      }
      return false

    },
    // 购买按钮（包含稍后支付和立即支付）
    async createOrderBuyOneBook(orderData) {
      const response = await createOrderBuynow(orderData)
      if (response.data.code === 0) {
        console.log("生成订单的请求的结果：", response);
        ElMessage({
          type: 'success',
          message: '订单已经生成'
        })

        return true
      } else {
        console.log("生成订单的请求的结果：", response);
        ElMessage({
          type: 'error', message: response.data.message,
          plain: true
        })
        return false
      }

    },
    // 购物车结算（包含稍后支付和立即支付）
    async createOrderCart(orderData) {
      const response = await createOrderFromCart(orderData)
      // console.log("购物车结算生成订单的请求的结果：", response);
      if (response.data.code === 0) {
        console.log("购物车结算生成订单的请求的结果：", response);
        ElMessage({
          type: 'success',
          message: '订单已生成',
          plain: true,
        })
        return true
      } else {

        ElMessage({
          type: 'error', message: response.data.message,
          plain: true
        })
        return false
      }
    },
    async deleteOrder(id) {
      const response = await deleteOrder(id)
      // console.log("删除订单的请求的结果：", response);
      if (response.data.code === 0) {
        console.log("删除订单的请求的结果：", response);
        // 更新订单列表
        this.fetchOrders()

        // ElMessage.success('删除成功')
        return true
      }
      // ElMessage.error('删除失败')
      return false
    },
    // 申请售后
    async applyAfterSale(orderData) {
      // console.log("申请售后的数据：", orderData);
      // 调用接口
      const response = await applyAfterSale(orderData)
      console.log("申请售后的请求的结果：", response);
      // 更新订单列表
      this.fetchOrders()

      if (response.data.code === 0) {
        ElMessage.success('申请售后成功')
      }
      return true
    },



  }
})